package ldh.im.base;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import ldh.im.dto.base.Req;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChannelGroupManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChannelGroupManager.class);
    private static ChannelGroupManager instance;

    private ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private ChannelGroupManager() {
    }

    public static ChannelGroupManager getInstance() {
        if (instance == null) {
            synchronized (ChannelGroupManager.class) {
                if (instance == null) {
                    instance = new ChannelGroupManager();
                }
            }
        }
        return instance;
    }

    public Channel getChannel(ChannelId channelId) {
        return channelGroup.find(channelId);
    }

    public boolean removeChannel(Channel channel) {
        return channelGroup.remove(channel);
    }

    public void addChannel(Channel channel) {
        channelGroup.add(channel);
    }

    public ChannelGroupFuture writeAndFlush(Req req, ChannelMatcher matcher) {
        return channelGroup.writeAndFlush(req, matcher);
    }

}
